#![allow(non_snake_case)]
use leptos::prelude::*;
use icondata as i;
use leptos_icons::*;
use shq_common::prelude::{Executor, RunProcess};

use crate::components::{loading::Loading, server_error::ServerError};
#[component]
pub fn FlowRunStep(
    #[prop(optional, into)] title: MaybeProp<String>,
    run_id: Signal<u64>,
    is_show: RwSignal<bool>,
    #[prop(default=600, into)] max_width: u32,
) -> impl IntoView {
    let process = Resource::new(
        move || run_id.get(),
        move |run_id| async move {
            let jval_res = get_run_process(run_id).await;
            jval_res
        },
    );
    let executor_view = move |executors: Vec<Executor>| {
        view! {
            <ul tabindex="0" class="bg-base-100 mt-2 w-full p-2 text-sm">
                {
                    executors.into_iter().map(|e| {
                        let (tsname, text_class) = match e.task_state {
                            shq_common::prelude::TaskStatus::None => ("未开始", "text-neutral"),
                            shq_common::prelude::TaskStatus::Doing => ("进行中", "text-primary"),
                            shq_common::prelude::TaskStatus::Done => ("已完成", "text-success"),
                            shq_common::prelude::TaskStatus::Back => ("已回退", "text-warning"),
                            shq_common::prelude::TaskStatus::Suspend => ("已中止", "text-error"),
                        };
                        let ts_class = format!("w-20 {}", text_class);
                        view! {
                            <li class="flex flex-row items-center space-x-1">
                                <span class="w-20">{e.user_name}</span>
                                <span class={ts_class}>{tsname}</span>
                                <span class="w-32">{e.submit_time}</span>
                                <span class="flex-1">{e.feed_back}</span>
                            </li>
                        }
                    }).collect_view()
                }
            </ul>
        }
    };
    let steps_view = move || {
        match process.get() {
            Some(res) => match res {
                Ok(rps) => view! {
                    <ol class="relative text-gray-500 border-s border-gray-200 dark:border-gray-700 dark:text-gray-400">
                        {
                            let steps=rps.steps;
                            steps.into_iter().map(|step| {
                                let color_name=match step.state {
                                    shq_common::prelude::StepState::None => "bg-neutral-content",
                                    shq_common::prelude::StepState::Doing => match rps.state {
                                        shq_common::prelude::FlowState::Runing => "bg-primary",
                                        shq_common::prelude::FlowState::Completed => "bg-primary",
                                        shq_common::prelude::FlowState::Suspended => "bg-error",
                                    },
                                    shq_common::prelude::StepState::Done => "bg-success",
                                };
                                let text_color=match step.state {
                                    shq_common::prelude::StepState::None => "text-black",
                                    shq_common::prelude::StepState::Doing => "text-white",
                                    shq_common::prelude::StepState::Done => "text-white",
                                };
                                let class_name=format!("absolute flex items-center justify-center w-8 h-8 {} rounded-full -start-4 ring-4 ring-white dark:ring-gray-900 dark:bg-green-900 {}", color_name, text_color);
                                let icon_view=move||{
                                    match step.state {
                                        shq_common::prelude::StepState::None => {
                                            view! { <Icon icon=i::RiUserUserFacesLine width="20px" height="20px"/> }
                                        }
                                        shq_common::prelude::StepState::Doing => {
                                            view! { <Icon icon=i::RiUserSettingsUserFacesLine width="20px" height="20px"/> }
                                        }
                                        shq_common::prelude::StepState::Done => {
                                            view! { <Icon icon=i::RiUserFollowUserFacesLine width="20px" height="20px"/> }
                                        }
                                    }
                                };
                                view! {
                                    <li class="mb-10 ms-6">
                                        <span class=class_name>
                                            {icon_view}
                                        </span>
                                        <h3 class="font-medium leading-tight">{step.name}</h3>
                                        {executor_view(step.executors)}
                                    </li>
                                }
                            }).collect_view()
                        }
                    </ol>
                }.into_any(),
                Err(err) => view! { <ServerError err_msg=err.to_string().into()/> }.into_any(),
            },
            None => view! { <Loading/> }.into_any(),
        }
    };
    view! {
        <div id="edit_modal" class="modal" class:modal-open=move||is_show.get()>
            <div class="modal-box overflow-hidden" style:max-width=move || format!("{}px", max_width)>
                <div class="flex items-center justify-between mb-4 rounded-t dark:border-gray-600">
                    <h3 class="text-xl font-medium text-gray-900 dark:text-white">
                        {title.get()}
                    </h3>
                    <button type="button" on:click=move |_| {is_show.set(false);}
                        class="text-gray-400 bg-transparent hover:bg-gray-200 hover:text-gray-900 rounded-lg text-sm w-8 h-8 ms-auto inline-flex justify-center items-center dark:hover:bg-gray-600 dark:hover:text-white">
                        <Icon icon=i::AiCloseCircleOutlined width="20px" height="20px"/>
                    </button>
                </div>
                <div class="modal-body mx-4">
                    <Suspense fallback=|| view! { <Loading/> }>
                        {steps_view}
                    </Suspense>
                </div>
            </div>
        </div>
    }
}

#[server(GetListDataForClient, "/api/protect")]
async fn get_run_process(run_id: u64) -> Result<RunProcess, ServerFnError> {
    let process = shq_workflow::get_process(run_id)
        .await
        .map_err(|e| ServerFnError::new(e.to_string()))?;
    Ok(process)
}
